package com.doubao.hardware.config;

import com.doubao.hardware.handler.MqttCallbackCustomReconnect;
import com.doubao.hardware.util.CommonUtil;
import com.doubao.hardware.util.MqttAuthUtil;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Data
public class IotMqConfig implements CommandLineRunner, ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(IotMqConfig.class);
    private static final String logTitle = "MQttIot信息: ";

    private ApplicationContext applicationContext;

    @Value("${mqtt.broker.url:}")
    private String serverURI;

    @Value("${mqtt.client.serverURI:}")
    private String clientServerURI;

    @Value("${mqtt.client.keepAliveInterval:60}")
    private int keepAliveInterval;

    @Value("${mqtt.client.connectionTimeout:30}")
    private int connectionTimeout;

    @Value("${mqtt.client.adp_type:thingidp}")
    private String adp_type;

    @Value("${mqtt.baidu.iot-core-id:}")
    private String IoTCoreId;

    @Value("${mqtt.baidu.device-key:}")
    private String DeviceKey;

    @Value("${mqtt.client.algorithm_type:MD5}")
    private String algorithm_type;

    @Value("${mqtt.baidu.device-secret:}")
    private String device_secret;

    @Value("${mqtt.baidu.topic:}")
    public String defaultTopic;

    private IotMqttClient iotMqttClient;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("MQTT配置: serverURI={}, clientServerURI={}, IoTCoreId={}, DeviceKey={}, defaultTopic={}",
                serverURI, clientServerURI, IoTCoreId, DeviceKey, defaultTopic);
        this.getMqtt();
    }

    public IotMqttClient getMqtt() {
        try {
            // 使用当前时间戳
            Integer mqtt_baid_Time = CommonUtil.getSecondTimestampTwo(new Date());

            // 使用工具类生成用户名和密码
            String username = MqttAuthUtil.generateUsername(
                    IoTCoreId, DeviceKey, mqtt_baid_Time, algorithm_type
            );

            String password = MqttAuthUtil.generatePassword(
                    DeviceKey, mqtt_baid_Time, algorithm_type, device_secret
            );

            // 生成稳定的客户端 ID
            String clientId = IoTCoreId + "_" + DeviceKey + "_" + mqtt_baid_Time;

            logger.info(logTitle + "正在构建MQTT连接，用户名: {}, 客户端ID: {}", username, clientId);

            MqttCallbackCustomReconnect mqttCallbackCustomReconnect =
                    applicationContext.getBean(MqttCallbackCustomReconnect.class);

            iotMqttClient = IotMqttClient.create()
                    .broker(serverURI)
                    .auth(username, password)
                    .clientId(clientId)
                    .cleanSession(true)
                    .automaticReconnect(false)
                    .callback(mqttCallbackCustomReconnect)
                    .connect();

            logger.info(logTitle + "MQTT连接成功");
            return iotMqttClient;
        } catch (Exception e) {
            logger.error(logTitle + "连接错误: {}", e.getMessage(), e);
            return null;
        }
    }

    public Boolean isConnected() {
        if (iotMqttClient == null || !iotMqttClient.isConnected()) {
            return false;
        }
        return true;
    }

    public void publish(String payload) {
        try {
            if (!isConnected()) {
                logger.info(logTitle + "MQTT未连接，尝试重新连接");
                getMqtt();
            }

            if (isConnected()) {
                logger.info(logTitle + "发送消息到主题: {}", defaultTopic);
                iotMqttClient.publish(defaultTopic, payload.getBytes(), 1, false);
                logger.info(logTitle + "消息发送成功");
            } else {
                logger.error(logTitle + "MQTT未连接，无法发送消息");
            }
        } catch (Exception e) {
            logger.error(logTitle + "发送消息失败: {}", e.getMessage(), e);
        }
    }
}